// 网络请求的封装
import axios from 'axios'
import store from '@/store'

// 初始化一个axios实例
let server = axios.create({
  timeout: 10000,
});

// 请求拦截器
// 请求地址的区别
server.interceptors.request.use(config => {
  config.baseURL = process.env.NODE_ENV === 'development' ? '' : 'https://api.iynn.cn/film'
  return config
})
// 给所有的请求添加token，请求头
server.interceptors.request.use(config => {

  if (config.url !== '/login') {
    config.headers.token = store.getters.token
  }

  return config
})

// 响应拦截器
server.interceptors.response.use(reponse => {

  // 统一去设置token值
  if(reponse.headers.token){
    store.commit('user/setToken',reponse.headers.token)
  }


  return reponse.data
}, err => Promise.reject(err))

/**
 * 进行get请求
 * @param {string} url 请求的url地址
 * @param {object} config 额外请求头配置
 * @returns promise
 * 
 * ```
 * # 示例
 * import {get} from './request.js'
 * get(url).then(res=>console.log(res))
 * ```
 */
export const get = (url, config = {}) => server.get(url, config)

/**
 * 进行post请求
 * @param {string} url 请求的url地址
 * @param {object} data 请求发送过去的data数据源
 * @param {object} config 额外请求头配置
 * @returns promise
 * 
 * ```
 * # 示例
 * import {post} from './request.js'
 * post(url,{id:1}).then(res=>console.log(res))
 * ```
 */
export const post = (url, data = {}, config = {}) => server.post(url, data, config)


export const remove = (url, data = {}, config = {}) => server.delete(url, data, config)

export const put = (url, data = {}, config = {}) => server.put(url, data, config)